<?php

class WechatController extends \BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */


    public function index()
    {
        //
        error_reporting(0);
        if($GLOBALS["HTTP_RAW_POST_DATA"]) {
            $this->response($GLOBALS["HTTP_RAW_POST_DATA"]);
        }else{
            $this->valid();
        }
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function response($postStr)
    {


        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $type = $postObj->MsgType;
        $event = $postObj->Event;

        //下班开关
//        if($type=='text'){
//            $this->auto($postObj);
//        }

        /**
         * 查询是否是绑定模块
         */

        if($type == 'text'){
            if($keyword == '水问'){
                $art = [
                    [
                        'title' => '纪录片《水问》一问，危机何时到来？',
                        'cover' => 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/18331858.jpg',
                        'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208764126&idx=1&sn=25a5add93212037b5f4a72de22f8514e'
                    ],
                    [
                        'title' => '二问，饮水能否安全？',
                        'cover' => 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/48584229.jpg',
                        'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208764126&idx=2&sn=17e179ff1965e4c0148dbb8887c7cdff'
                    ],
                    [
                        'title' => '三问，生灵是否安宁？',
                        'cover' => 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/443193.jpg',
                        'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208764126&idx=3&sn=1895559304d209df326bfd941cd650b6'
                    ],
                    [
                        'title' => '四问，江河如何安澜？',
                        'cover' => 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/22721929.jpg',
                        'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208764126&idx=4&sn=39b20ef05d861b56a204428b7a019415'
                    ],
                    [
                        'title' => '五问，水究竟属于谁？',
                        'cover' => 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/89073059.jpg',
                        'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208764126&idx=5&sn=46a7e2c0e4d4c7959597f7d58f80541c'
                    ],
                    [
                        'title' => '六问，大国水网有多远？',
                        'cover' => 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/66589435.jpg',
                        'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208764126&idx=6&sn=801867f088811ad44cdb6268d4c4b370'
                    ],
                    [
                        'title' => '七问，节水难在何处？',
                        'cover' => 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/38098640.jpg',
                        'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208764126&idx=7&sn=9231b3da708cc4d5c1835ba3ef045369'
                    ],
                    [
                        'title' => '八问，水的答案在哪里?',
                        'cover' => 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/54740653.jpg',
                        'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208764126&idx=8&sn=09a6bbf2039198eeed71c09a1341d267'
                    ],
                ];
                $this->areas_morearts($art,$postObj);
            }
            if($keyword == '水知道答案'){

                $title = '《水知道答案》震惊并影响世界的发现！(视频完整版)';
                $pic = 'http://7u2rj5.com2.z0.glb.qiniucdn.com/15-8-21/18788935.jpg';
                $url = 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=208693530&idx=1&sn=d495c141ca86310ba6997c34f3190286#rd';
                $digest = '震惊并影响全世界的发现：《水知道答案》观后感！杨郑莉：　　《水知道答案》又一次揭示了精神与物质之间具有联系，';

                $this->simple_onart($title,$digest,$pic,$url,$postObj);
            }
            if($keyword == '安装' || $keyword == '试用' || $keyword == '购机'){

            }
            $length = strlen($keyword);
            if($length == 8){//为绑定码长度
                $keyword = strtolower($keyword);
                $count = Mount::where('bangding',$keyword)->count();
                if($count == 1){//是否有此机器绑定码
                    $mount = Mount::where('bangding',$keyword)->first();
                    $customer_count = Customer::where('openid',$fromUsername)->count();//判断是否已经注册过
                    if($customer_count == 0){//如果未注册
                        $city = Area::find($mount->city);
                        $customer = New Customer();
                        $customer->name = $mount->mount_name;
                        $customer->mobile = $mount->mount_mobile;
                        $customer->openid = $fromUsername;
                        $customer->province = $city->father_id;
                        $customer->city = $city->id;
                        $customer->area = $mount->section_id;
                        $customer->invite = 0;
                        $customer->save();


                        $get_customer = Customer::find($customer->id);
                        $get_customer->invite = sprintf('%06s', $customer->id);
                        $get_customer->save();
                        $mount->customer_id = $customer->id;
                        $mount->save();
                        $text = '恭喜，机器已与您的微信绑定';
                    }else{
                        $customer = Customer::where('openid',$fromUsername)->first();
                        $mount->customer_id = $customer->id;
                        $mount->save();
                        $text = '恭喜，机器已与您的微信绑定';
                    }
                    $this->response_text($text, $postObj);
                }
            }
        }


        /**
         * 左邻右舍模块
         */
        if($type == 'location'){

            $pub = Pub::find(1);

            $PATH = $pub->path;
            $lat = $postObj->Location_X;
            $lat = (float)$lat;
            $lon = $postObj->Location_Y;
            $lon = (float)$lon;
            $text = '';
//            $sql='select * from `ae_areas` where x>0 order by (2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*('.$lon.'-y)/360),2)+COS(PI()*'.$lat.'/180)* COS(y * PI()/180)*POW(SIN(PI()*('.$lat.'-x)/360),2)))) asc limit 0,10';
//            $sql='SELECT *, (POWER(MOD(ABS(y - '.$lon.'),360),2) + POWER(ABS(x - '.$lat.'),2)) AS distance FROM `ae_areas` where x > 0 ORDER BY distance LIMIT 10';
            $sql='SELECT *, ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$lat.'*PI()/180-x*PI()/180)/2),2)+COS('.$lat.'*PI()/180)*COS('.$lat.'*PI()/180)*POW(SIN(('.$lon.'*PI()/180-y*PI()/180)/2),2)))*1000) AS juli FROM `ae_areas` where x> 0 ORDER BY juli ASC limit 10;';

//            $this->response_text($sql,$postObj);
//            exit;
            $areas = DB::select($sql);
            foreach($areas as $key => $area){
                $rate = rand(90,99).'%';
                $areaarts[$key]['title'] = '【'.$area->name.'】'.'装机数'.$area->mount_count;
                $areaarts[$key]['cover'] = $PATH.$area->cover;
//                $areaarts[$key]['url'] = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=area_' . $area->id . '#wechat_redirect';
                $areaarts[$key]['url'] = 'http://crm.leaderphos.com/machines?area_id='.$area->id;
            }
            $this->areas_morearts($areaarts,$postObj);

        }

        //事件
        if($type =='event') {

            //扫码事件
            if ('subscribe' == $postObj->Event) {
                if($postObj->EventKey) {
                    $EventKey = $postObj->EventKey;
                    $ar = explode('_', (string)$EventKey);
                    $num = $ar[1];
                    if (is_numeric($num)) {

                        $time = time();
                        $EventKey = $num;
                        if ($EventKey >= 10000 && $EventKey <= 99999) {//产品二维码
                            $count = Work::where('openid', $fromUsername)->count();
                            if ($count > 0) {//判断是否是工人
                                $work = Work::where('openid', $fromUsername)->first();
                                $mountcount = Mount::where('code', $EventKey)->count();
                                if ($mountcount == 1) {//判断是否存在二维码
                                    $service = Service::findservice($EventKey);
                                    if ($work->id == $service->worker_id) {
                                        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=' . $service->id . '#wechat_redirect';
                                        $this->simple_onart('当前机器', '待处理工单', $service->customer->avatar, $url, $postObj);
                                    } else {
                                        $text = '当前无权处理该机';
                                    }
                                } else {
                                    $services = Service::findservices($work->id);
                                    $this->simple_morearts($services, $postObj, $fromUsername, $EventKey);
                                }
                            } else {
                                $customer_count = Customer::where('openid',$fromUsername)->count();
                                if($customer_count == 1){//判断是否喂客户
                                    $mount_count = Mount::where('code',$EventKey)->count();
                                    if($mount_count == 0){
                                        $text = '该二维码无对应机器';
                                    }else{
                                        $customer = Customer::where('openid',$fromUsername)->first();
                                        $mount = Mount::where('code',$EventKey)->first();
                                        $mount->customer_id = $customer->id;
                                        $mount->save();
                                        $service = Service::where('mount_id',$mount->id)->first();
                                        $service->customer_id = $customer->id;
                                        $service->save();
                                        $text = '该机已绑定客户'.$customer->name;
                                    }
                                }else{//推送完善信息
                                    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=request#wechat_redirect';
                                    $this->simple_onart('请先填写资料','完成后扫一扫','',$url,$postObj);
                                }
                            }


                            $this->response_text($text, $postObj);


//                    exit;
//                    $code = Code::where('start','<=',$EventKey)
//                        ->where('stop','>=',$EventKey)
//                        ->firstOrFail();
//
//                    $customer = Customer::where('openid',$fromUsername)->firstOrFail();
//                    $mount = Mount::where('customer_id',$customer->id)
//                        ->where('state',0)
//                        ->firstOrFail();
//                    $mount->machine_id = $code->machine_id;
//                    $mount->code = $EventKey;
//                    $mount->save();
//
//                    for($i = 1; $i<= $code->machine->count;$i++){
//                        $cname = 'filter'.$i;
//                        $data[] = array('mount_id'=>$mount->id,'commodity_id'=>$code->machine->$cname,'start_time'=>$time,'state'=>1);
//                    }
//
//                    DB::table('filterins')->insert($data);
//
//
//                    $this->response_text('关联成功',$postObj);
                        }elseif($EventKey < 10000){
                            $user = User::find($EventKey);
                            if($user->permissions == '{"section":1}') {

                                $count = Customer::where('openid', $fromUsername)->count();
                                if ($count == 0) {
                                    $customer = New Customer();
                                    $customer->openid = $fromUsername;
                                    $customer->province = $user->province;
                                    $customer->city = $user->city;
                                    $customer->area = $user->area;
                                    $customer->invite = 0;
                                    $customer->save();


                                    $get_customer = Customer::find($customer->id);
                                    $get_customer->invite = sprintf('%06s', $customer->id);
                                    $get_customer->save();
                                }
                                $user->subscribe = $user->subscribe+1;
                                $user->save();
//                                $text = '感谢您关注雷谛净水，时时掌握水资讯。
//点击“免费安装”可了解净水机免费赠送活动。
//好水让家人更健康，雷谛净水为您保家护航';
//
//                                $this->response_text($text,$postObj);
                                $pic = 'http://7vij71.com2.z0.glb.qiniucdn.com/leaderphos/pic_sub.jpg';
                                $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=supplement#wechat_redirect';
                                $this->simple_onart('感谢您关注雷谛净水，时时掌握水资讯', '点击图文完善个人信息，完成后增加50积分', $pic, $url, $postObj);
                            }
                        }
//                $this->response_text($EventKey,$postObj);
                        $id = 99999999-$EventKey;
                        $work = Work::find($id);
                        $text = $work->name."员工绑定成功";
                        $work->openid = $fromUsername;
                        $da = Wechat::get_user($fromUsername);
                        $work->avatar = $da->headimgurl;
                        $work->save();
                        $this->response_text($text,$postObj);
                    }else{



                        $post = array(
                            array(
                                'pic' => 'http://7vij71.com2.z0.glb.qiniucdn.com/leaderphos/pic_sub.jpg',
                                'url' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=supplement#wechat_redirect',
                                'title' => '感谢您关注雷谛净水，时时掌握水资讯，点击图文完善信息，增加积分。'
                            ),
                            array(
                                'pic' => 'http://7vij71.com2.z0.glb.qiniucdn.com/leaderphos/old.png',
                                'url' => 'http://mp.weixin.qq.com/s?__biz=MzA3MTM4MzgwMw==&mid=204754163&idx=1&sn=81c520c5edf4b9045d874635e3a1733c&key=b2574200810f04e81a91622f224010b0f8d2b77403e967ce4a546381f401d0e4816d57fe6f7071403263252e8cccfd08&ascene=0&uin=MTUwNzY1MzYw&devicetype=iMac+MacBookAir6%2C2+OSX+OSX+10.10.2+build(14C1514)&version=11020012&pass_ticket=t7nx%2B6flp2g3S9uHnz01fnnKVptW3h8JJ3MNerXQBao%3D',
                                'title' => '雷谛老客户绑定微信流程'
                            ),
                        );

                        $this->morearts($post,$postObj);
                    }
                }
            }
//                $apply = Apply::where('type',1)->firstOrFail();
//                if($apply->restype == 1){
//                    $this->response_text($apply->text,$postObj);
//                }elseif($apply->restype == 2){
//                    $push= Push::find($apply->mid);
//                    $this->response_arts($push,$postObj);
//                }


        }


        //扫码事件
        if('SCAN'== $event){

            if($postObj->EventKey) {
                $time = time();
                $EventKey = $postObj->EventKey;
                if($EventKey >= 10000 && $EventKey <= 99999 ){//产品二维码
                    $count = Work::where('openid',$fromUsername)->count();
                    if($count > 0){//判断是否是工人
                        $work = Work::where('openid',$fromUsername)->first();
                        $mountcount = Mount::where('code',$EventKey)->count();
                        if($mountcount == 1) {//判断是否存在二维码
                            $service = Service::findservice($EventKey);
                            if($work->id == $service->worker_id){
                                $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state='.$service->id.'#wechat_redirect';
                                $this->simple_onart('当前机器','待处理工单',$service->customer->avatar,$url,$postObj);
                            }else{
                                $text = '当前无权处理该机';
                            }
                        }else{
                            $services = Service::findservices($work->id);
                            $this->simple_morearts($services,$postObj,$fromUsername,$EventKey);
                        }
                    }else{
                        $customer_count = Customer::where('openid',$fromUsername)->count();
                        if($customer_count == 1){//判断是否喂客户
                            $mount_count = Mount::where('code',$EventKey)->count();
                            if($mount_count == 0){
                                $text = '该二维码无对应机器';
                            }else{
                                $customer = Customer::where('openid',$fromUsername)->first();
                                $mount = Mount::where('code',$EventKey)->first();
                                $mount->customer_id = $customer->id;
                                $mount->save();
                                $service_count = Service::where('mount_id',$mount->id)->count();

                                if($service_count > 0){
                                    $service = Service::where('mount_id',$mount->id)->first();
                                    $service->customer_id = $customer->id;
                                    $service->save();
                                }

                                $text = '该机已绑定客户'.$customer->name;
                            }
                        }else{//推送完善信息
                            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=request#wechat_redirect';
                            $this->simple_onart('请先填写资料','完成后扫一扫','',$url,$postObj);
                        }
                    }


                    $this->response_text($text,$postObj);


//                    exit;
//                    $code = Code::where('start','<=',$EventKey)
//                        ->where('stop','>=',$EventKey)
//                        ->firstOrFail();
//
//                    $customer = Customer::where('openid',$fromUsername)->firstOrFail();
//                    $mount = Mount::where('customer_id',$customer->id)
//                        ->where('state',0)
//                        ->firstOrFail();
//                    $mount->machine_id = $code->machine_id;
//                    $mount->code = $EventKey;
//                    $mount->save();
//
//                    for($i = 1; $i<= $code->machine->count;$i++){
//                        $cname = 'filter'.$i;
//                        $data[] = array('mount_id'=>$mount->id,'commodity_id'=>$code->machine->$cname,'start_time'=>$time,'state'=>1);
//                    }
//
//                    DB::table('filterins')->insert($data);
//
//
//                    $this->response_text('关联成功',$postObj);
                }elseif($EventKey < 10000){
                    $user = User::find($EventKey);
                    if($user->permissions == '{"section":1}') {

                        $count = Customer::where('openid', $fromUsername)->count();
                        if ($count == 0) {
                            $customer = New Customer();
                            $customer->openid = $fromUsername;
                            $customer->province = $user->province;
                            $customer->city = $user->city;
                            $customer->area = $user->area;
                            $customer->invite = 0;
                            $customer->save();

                            $get_customer = Customer::find($customer->id);
                            $get_customer->invite = sprintf('%06s', $customer->id);
                            $get_customer->save();
                        }

                        $text = '感谢您关注雷谛净水，时时掌握水资讯。
点击“免费安装”可了解净水机免费赠送活动。
好水让家人更健康，雷谛净水为您保家护航';

                        $this->response_text($text,$postObj);
                    }
                }else{
//                $this->response_text($EventKey,$postObj);
                    $id = 99999999-$EventKey;
                    $work = Work::find($id);
                    $text = $work->name."员工绑定成功";
                    $work->openid = $fromUsername;
                    $da = Wechat::get_user($fromUsername);
                    $work->avatar = $da->headimgurl;
                    $work->save();
                    $this->response_text($text,$postObj);
                }
            }
        }




        if($type == 'image' ) {


            $count = Work::where('openid',$fromUsername)->count();
            if($count != 0){
                $work = Work::where('openid',$fromUsername)->first();
                $s_count = Service::where('worker_id',$work->id)->where('type',1)->where('state',3)->count();
                if($s_count != 0){
                    $service = Service::where('worker_id',$work->id)->where('type',1)->where('state',3)->orderBy('updated_at', 'DESC')->first();
                    $picture = new Picture();
                    $picture->path = $postObj->PicUrl;
                    $picture->mount_id = $service->mount_id;
                    $picture->change = 0;
                    $picture->save();
                }
            }
//
//            $count = Service::select('services.*')
//                ->join('customers', 'services.uid', '=', 'customers.id','left')
//                ->where('services.if_image', '1')
//                ->where('services.image_sended', '0')
//                ->where( 'customers.openid',$fromUsername)
//                ->count();
//            if($count == 0){
//                $this->auto($postObj);
//            }
//
//            $image = new Image;
//            $image->openid = $postObj->FromUserName;
//            $image->pic = $postObj->PicUrl;
//            $image->update_time = time();
//            $image->save();
            $text_hero = '装机秀上传成功';
            $this->response_text($text_hero,$postObj);
        }




        if($event == 'CLICK'){
            $keyword = $postObj->EventKey;
        }

        $mcount = Material::where('key',$keyword)->count();

        if(0 != $mcount){
            $material = Material::where('key',$keyword)->firstOrFail();
            $this->material_onart($material,$postObj);
        }

//        $count = Apply::where('keyword',$keyword)->count();
//        if(0 != $count){
//            $apply = Apply::where('keyword',$keyword)->firstOrFail();
//            if($apply->restype == 1){
//                $this->response_text($apply->text,$postObj);
//            }elseif($apply->restype == 2){
//                $push= Push::find($apply->mid);
//                $this->response_arts($push,$postObj);
//            }
//        }

        //开启多客服
        $this->service_text($postObj);
        return;

    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
            if(!empty( $keyword ))
            {
                $msgType = "text";
                $contentStr = "Welcome to wechat world!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo "Input something...";
            }

        }else {
            echo "";
            exit;
        }
    }


    /**
     *  @desc 根据两点间的经纬度计算距离
     *  @param float $lat 纬度值
     *  @param float $lng 经度值
     */
    function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000; //approximate radius of earth in meters

        /*
          Convert these degrees to radians
          to work with the formula
        */

        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;

        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        /*
          Using the
          Haversine formula

          http://en.wikipedia.org/wiki/Haversine_formula

          calculate the distance
        */

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = 'bosch';
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function response_arts($res,$postObj){
        $r = json_decode($res->content);
        if($res->type == 2){
            $this->response_morearts($r,$postObj);
        }else{
            $this->response_oneart($r,$postObj);
        }
    }


//回复尝鲜多图文
    function morearts($res,$postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>
            ITEM
            </Articles>
            </xml>";
        $count = count($res);
        $resstr =  sprintf($textTpl, $fromUsername, $toUsername, time(), "news", $count );
        $item = '';
        $subitem = "<item>
            <Title><![CDATA[%s]]></Title>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>";
        foreach ($res as $r){

            $item.=sprintf($subitem, $r['title'], $r['pic'], $r['url'] );
        }


        $resstr = str_replace('ITEM', $item, $resstr);
        echo $resstr;
    }

    //回复文本
    function response_text($txt,$postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0</FuncFlag>
            </xml>";
        $res = sprintf($textTpl, $fromUsername, $toUsername, time(), "text", trim($txt));
        //Log::error($res);
        echo $res;
    }

    function simple_onart($title,$digest,$pic,$url,$postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>
            ITEM
            </Articles>
            </xml>";
        $resstr =  sprintf($textTpl, $fromUsername, $toUsername, time(), "news", 1);
        $subitem = "<item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>";
        $item=sprintf($subitem, $title, $digest, $pic , $url );
        $resstr = str_replace('ITEM', $item, $resstr);
        echo $resstr;
    }


    function material_onart($material,$postObj){

        $PATH = "http://aebo.qiniudn.com/";
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>
            ITEM
            </Articles>
            </xml>";
        $resstr =  sprintf($textTpl, $fromUsername, $toUsername, time(), "news", 1);
        $subitem = "<item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>";
        if($material->url != ''){
            $url = $material->url;
        }else{
            $url = route('materials.show', $material->id);
        }
        $item=sprintf($subitem,$material->title, $material->dec, $PATH.$material->cover , $url );
        $resstr = str_replace('ITEM', $item, $resstr);
        echo $resstr;
    }

    //回复单图文
    function response_oneart($r,$postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>
            ITEM
            </Articles>
            </xml>";
        $resstr =  sprintf($textTpl, $fromUsername, $toUsername, time(), "news", 1);
        $subitem = "<item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>";
        if($r->content_source_url != ''){
            $content_source_url = $r->content_source_url;
        }else{
            $content_source_url = route('materials.show', $r->mic);
        }
        $item=sprintf($subitem, $r->title, $r->digest, asset($r->pic) , $content_source_url );
        $resstr = str_replace('ITEM', $item, $resstr);
        echo $resstr;

    }
//回复多图文
    function response_morearts($res,$postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>
            ITEM
            </Articles>
            </xml>";
        $resstr =  sprintf($textTpl, $fromUsername, $toUsername, time(), "news", count($res));
        $item = '';
        $subitem = "<item>
            <Title><![CDATA[%s]]></Title>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>";
        foreach ($res as $r){

            if($r->content_source_url != ''){
                $content_source_url = $r->content_source_url;
            }else{
                $content_source_url = route('materials.show', $r->mic);
            }
            $item.=sprintf($subitem, $r->title,asset($r->pic),  $content_source_url );
        }
        $resstr = str_replace('ITEM', $item, $resstr);
        echo $resstr;
    }

//回复多图文
    function simple_morearts($res,$postObj,$from,$code){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>
            ITEM
            </Articles>
            </xml>";
        $count = count($res)+1;
        $resstr =  sprintf($textTpl, $fromUsername, $toUsername, time(), "news", $count );
        $item = '';
        $subitem = "<item>
            <Title><![CDATA[%s]]></Title>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>";
        foreach ($res as $r){

            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state='.$r->id.'_'.$code.'#wechat_redirect';
            $item.=sprintf($subitem, '装机用户:'.$r->mount->mount_name,$r->customer->avatar,  $url );
        }
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=new_'.$r->worker_id.'_'.$code.'#wechat_redirect';
        $new_mount_pic = 'http://7vij71.com2.z0.glb.qiniucdn.com/leaderphos/new_mount.png';
        $item .=sprintf($subitem, '新增一条装机记录',$new_mount_pic,  $url );


        $resstr = str_replace('ITEM', $item, $resstr);
        echo $resstr;
    }

    //回复多图文
    function areas_morearts($res,$postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>
            ITEM
            </Articles>
            </xml>";
        $resstr =  sprintf($textTpl, $fromUsername, $toUsername, time(), "news", count($res));
        $item = '';
        $subitem = "<item>
            <Title><![CDATA[%s]]></Title>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>";
        foreach ($res as $r){
            $item.=sprintf($subitem, $r['title'],$r['cover'],  $r['url']);
        }
        $resstr = str_replace('ITEM', $item, $resstr);
        echo $resstr;
    }
    function auto($postObj){
        $apply = Apply::where('type',3)->firstOrFail();
        if($apply->pipei == 1){
            if($apply->restype == 1){
                $this->response_text($apply->text,$postObj);
            }elseif($apply->restype == 2){
                $push= Push::find($apply->mid);
                $this->response_arts($push,$postObj);
            }
        }
    }

    function service_text($postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $textTpl = "<xml>
	<ToUserName><![CDATA[%s]]></ToUserName>
	<FromUserName><![CDATA[%s]]></FromUserName>
	<CreateTime>%s</CreateTime>
	<MsgType><![CDATA[%s]]></MsgType>
	</xml>";
        $res = sprintf($textTpl, $fromUsername, $toUsername, time(), "transfer_customer_service");
        //Eventog::error($res);
        echo $res;
    }


    function random($length)
    {
        $month = date('ym');
        $hash = $month;
        $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
        $max = strlen($chars) - 1;
        mt_srand((double)microtime() * 1000000);
        for($i = 0; $i < $length; $i++)
        {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }


}
